import { useRef, useState } from 'react';

import { useAntdTable, useRequest } from 'ahooks';
import { Button, DatePicker, Form, Input, Modal, Radio, Space, Table } from 'antd';
import { Dayjs } from 'dayjs';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import { proShiftTeamPage } from '@/services/bizApi/shengchanbanzujiekou';
import { proPerformancePage, proPerformanceUpdate } from '@/services/bizApi/shengchanjixiaojiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import Edit, { EditRef } from './edit';
import Evaluation, { EvaluationRef } from './evaluate';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ProPerformanceEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const evaluation = useRef<EvaluationRef>(null);
  const [filter] = Filter.useForm();
  const [ModalForm] = Form.useForm();
  const [currentId, setCurrentId] = useState('');
  const [currentType, setCurrentType] = useState(0);
  const [visiableModal, setVisiableModal] = useState(false);
  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );
  const orgDeptInfo = useRequest(
    async () => {
      const res = await orgDeptInfoTreeList();

      return res?.data;
    },
    {
      refreshDeps: []
    }
  );
  const table = useAntdTable(
    async ({ current, pageSize }, { id, issueTime, ...formData }) => {
      const [beginTime, endTime] = ((issueTime as [Dayjs?, Dayjs?]) || []).map((v) =>
        v?.format('YYYY-MM-DD HH:mm:ss')
      );
      const res = await proPerformancePage({
        ...formData,
        ...id,
        beginTime,
        endTime,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  const handleModal = (id: string, type: number) => {
    setCurrentType(type);
    setCurrentId(id);
    ModalForm.resetFields();
    setVisiableModal(true);
  };

  return (
    <>
      {/* 筛选 */}
      <Filter onFinish={onSearch} form={filter}>
        <Filter.Item name="issueTime">
          <DatePicker.RangePicker showTime placeholder={['绩效时间', '绩效时间']} />
        </Filter.Item>
        <ProFormSelect
          name="teamId"
          label=""
          placeholder="请班组名称"
          width={180}
          request={async () => {
            const res = await proShiftTeamPage({
              page: 1,
              size: 1000
            });

            return (
              res.data?.records?.map((item) => ({
                value: item.id,
                label: item.name
              })) || []
            );
          }}
        />
        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            render: (text, record, index) => `${index + 1}`,
            width: 80
          },
          {
            title: '班组名称',
            dataIndex: 'teamName',
            width: 120
          },
          {
            title: '班组总得分',
            dataIndex: 'teamScore',
            width: 120
          },
          {
            title: '绩效时间',
            dataIndex: 'performanceTime',
            width: 180
          },
          {
            title: '工艺消耗品(40分)',
            children: [
              {
                title: '原辅料吨水消耗(20分)及排名',
                dataIndex: 'yfldsxh',
                key: 'yfldsxh',
                width: 220,
                render: (text, record) => {
                  return `${text}(${record.yfldsxhRank})`;
                }
              },
              {
                title: '电能吨水消耗(10分)及排名',
                dataIndex: 'dndsxh',
                key: 'dndsxh',
                width: 220,
                render: (text, record) => {
                  return `${text}(${record.dndsxhRank})`;
                }
              },
              {
                title: '自来水吨水消耗(10分)及排名',
                dataIndex: 'zlsdsxh',
                key: 'zlsdsxh',
                width: 220,
                render: (text, record) => {
                  return `${text}(${record.zlsdsxhRank})`;
                }
              }
            ]
          },
          {
            title: '工艺运行稳定指标-工艺控制(60分)',
            children: [
              {
                title: '一、二级DO控制(20分)',
                dataIndex: 'yejdokz',
                key: 'yejdokz',
                width: 180
              },
              {
                title: 'MBR膜池运行稳定性(10分)',
                dataIndex: 'mbrmcyxwdx',
                key: 'mbrmcyxwdx',
                width: 220
              },
              {
                title: 'Fendon产水COD控制效果(10分)',
                dataIndex: 'fdcscodkzxg',
                key: 'fdcscodkzxg',
                width: 220
              },
              {
                title: '气浮刮泥控水指标(10分)',
                dataIndex: 'qfgnkszb',
                key: 'qfgnkszb',
                width: 220
              },
              {
                title: '处理水量效率(10分)',
                dataIndex: 'clslxl',
                key: 'clslxl',
                width: 180
              }
            ]
          },
          {
            title: '过程控制(30分)',
            children: [
              {
                title: '激励指标(10分)',
                dataIndex: 'jlzb',
                key: 'jlzb',
                width: 180
              },
              {
                title: '惩罚指标(20分)',
                dataIndex: 'cfzb',
                key: 'cfzb',
                width: 180
              }
            ]
          },
          {
            title: '否决指标',
            children: [
              {
                title: '在线监测排放指标超标',
                dataIndex: 'zxjcpfzbcb',
                key: 'zxjcpfzbcb',
                width: 180,
                render: (text) => {
                  return text === 0 ? '否' : '是';
                }
              },
              {
                title: '出现安全环保事故',
                dataIndex: 'cxaqhbsg',
                key: 'cxaqhbsg',
                width: 180,
                render: (text) => {
                  return text === 0 ? '否' : '是';
                }
              },
              {
                title: '当月非生产原因存水不超过3000吨',
                dataIndex: 'dyfscyycsbcgsqd',
                key: 'dyfscyycsbcgsqd',
                width: 250,
                render: (text) => {
                  return text === 0 ? '否' : '是';
                }
              }
            ]
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() && (
                    <Text
                      type="primary"
                      onClick={() => {
                        handleModal(row.id as unknown as string, 1);
                      }}
                    >
                      是否安全环保事故
                    </Text>
                  )}
                  {permission.check() && (
                    <Text
                      type="primary"
                      onClick={() => {
                        handleModal(row.id as unknown as string, 2);
                      }}
                    >
                      是否存水超标
                    </Text>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
      <Evaluation ref={evaluation} />

      <Modal
        width={500}
        title="是否违规"
        open={visiableModal}
        footer={null}
        onCancel={() => {
          setVisiableModal(false);
        }}
      >
        <Form
          form={ModalForm}
          onFinish={async (values) => {
            console.log(values);
            await proPerformanceUpdate({ ...values, id: currentId });
            store.app?.message.success('操作成功');
            setVisiableModal(false);
            table.refresh();
          }}
        >
          {currentType === 1 ? (
            <>
              <Form.Item
                name="cxaqhbsg"
                label="是否出现安全环保事故"
                rules={[{ required: true, message: '请选择是否出现安全环保事故' }]}
              >
                <Radio.Group>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item
                name="cxaqhbsgRemark"
                label="备注"
                rules={[{ required: true, message: '请输入备注' }]}
              >
                <Input.TextArea placeholder="请输入备注" autoSize={{ minRows: 2, maxRows: 4 }} />
              </Form.Item>
            </>
          ) : (
            <>
              <Form.Item
                name="dyfscyycsbcgsqd"
                label="是否当月非生产原因存水不超过3000吨"
                rules={[{ required: true, message: '请选择是否当月非生产原因存水不超过3000吨' }]}
              >
                <Radio.Group>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item
                name="dyfscyycsbcgsqdRemark"
                label="备注"
                rules={[{ required: true, message: '请输入备注' }]}
              >
                <Input.TextArea placeholder="请输入备注" autoSize={{ minRows: 2, maxRows: 4 }} />
              </Form.Item>
            </>
          )}

          <Form.Item style={{ textAlign: 'center' }}>
            <Space>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button onClick={() => setVisiableModal(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default Page;
